package com.sinping.qh.repository.mongo.records.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.dto.admin.user.ApiUserInfolistDto;
import com.sinping.qh.query.base.QueryParams;
import com.sinping.qh.repository.mongo.RectifyReviewRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jiahuaiqing
 * @create 2018/7/15
 */
@Service
public class RectifyReviewRepositoryImpl {

    @Autowired
    RectifyReviewRepository rectifyReviewRepository;

    @Autowired
    private MongoTemplate template;

    /**
     * 查询整改复查表中 hidden_danger_id,re_type相等，按创建时间倒序排序
     *
     * @param hiddenDangerId
     * @param clazz
     * @param targetClazz
     * @param <T>
     * @return
     */
    public <T> List<T> findRectifyReview(String hiddenDangerId, String reType, Class<?> clazz, Class<T> targetClazz) {
        try {
            List<AggregationOperation> operations = Lists.newArrayList();

            Criteria mainCriteria = new Criteria();
            Criteria one = Criteria.where("hidden_danger_id").is(hiddenDangerId);
            Criteria two = Criteria.where("re_type").is(reType);
            mainCriteria.andOperator(one, two);

            operations.add(Aggregation.match(mainCriteria));

            //这是排序代码
            SortOperation sortOperation = new SortOperation(new Sort(Sort.Direction.DESC, "gmt_created"));
            operations.add(sortOperation);


            Aggregation aggregation = Aggregation.newAggregation(operations);


            String table = template.getCollectionName(clazz);
            AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);
            return results.getMappedResults();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
